﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Exhibition.Dao.ViewModel;
using AutoMapper;
namespace Exhibition.Dao
{

    public class AdminUserDao
    {


        public AdminUserDao()
        {

            Mapper.CreateMap<E_AdminUser, AdminUserModel>();
        }
        public List<E_AdminUser> GetList(int startIndex, int maxRow, out int recordcount)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                recordcount = edm.E_AdminUser.Count();

                return edm.E_AdminUser.OrderByDescending(s => s.Id).Skip(startIndex).Take(maxRow).ToList();

            }

        }


        public AdminUserModel GetOneById(int id)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_AdminUser.FirstOrDefault(s => s.Id == id);
                return Mapper.Map<E_AdminUser, AdminUserModel>(query);
            }

        }


        public int Save(AdminUserModel obj)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_AdminUser.FirstOrDefault(s => s.Id == obj.Id);

                if (query == null)
                {


                    query = new E_AdminUser();

                    edm.AddToE_AdminUser(query);

                }


                query.UserName = obj.UserName;

                query.PassWord = obj.PassWord;

                query.RealName = obj.RealName;

                
                query.IsStatus = obj.Status;
                if (obj.Id == 0)
                {
                    query.CreateTime = obj.CreateTime;
                    query.CreateUserId = obj.CreateUserId;
                }
                query.RoleId = obj.RoleId;

                query.Email = obj.Email;
                
                edm.SaveChanges();

                return query.Id;


            }

        }

        public AdminUserModel UserLogin(string uname, string pwd)
        {
            using (ExhibitionEntities edm = new ExhibitionEntities())
            {
                var query = edm.E_AdminUser.Where(s=>s.UserName==uname&&s.PassWord==pwd&&s.IsStatus==0);
                return Mapper.Map<E_AdminUser, AdminUserModel>(query.FirstOrDefault());
            }
        }


        public int DelById(int id)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_AdminUser.FirstOrDefault(s => s.Id == id);

                if (query != null)
                {


                    edm.DeleteObject(query);


                }


                return edm.SaveChanges();


            }

        }


    }

}

